package com.link.play.fit.ai.ui.dialog

import android.app.Dialog
import android.os.Bundle
import android.text.Editable
import android.text.Selection
import android.text.TextUtils
import android.text.TextWatcher
import android.text.style.LineHeightSpan
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.DialogFragment
import com.link.play.fit.ai.R
import com.link.play.fit.ai.databinding.DialogChangeServingBinding
import kotlin.properties.Delegates

class ChangeServingDialog : DialogFragment() {


    //回调
    var result: ((Int) -> Unit)? = null

    //数量
    var num: Int = 0

    //记录原始数量
    var oldNum: Int = 0

    //单位
    var label: String = ""

    var selectBtn: View? = null
    var BtnList = mutableListOf<AppCompatButton>()
    lateinit var binding: DialogChangeServingBinding
    var density: Float = 0.0f
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext(), R.style.ChangeServingDialog)
        dialog.window?.setWindowAnimations(R.style.DialogAnimation)
        return dialog
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        density = resources.displayMetrics.density
        val window = dialog?.window ?: return null
        val lp = window.attributes
        lp.apply {
            width = WindowManager.LayoutParams.MATCH_PARENT
            height = WindowManager.LayoutParams.MATCH_PARENT
        }
        window.attributes = lp
        window.setGravity(Gravity.CENTER)
        binding = DialogChangeServingBinding.inflate(inflater)
        BtnList.add(binding.btn1x)
        BtnList.add(binding.btn3x)
        BtnList.add(binding.btn5x)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.btnCancel.setOnClickListener {
            dismiss()
        }
        binding.btnSure.setOnClickListener {
            result?.invoke(num)
            dismiss()
        }
        dialog?.setCanceledOnTouchOutside(true)
        dialog?.setOnKeyListener { a, b, c ->
            if (b == KeyEvent.KEYCODE_BACK && c.action == KeyEvent.ACTION_UP) {
                a.dismiss()
                true
            } else {
                false
            }
        }
        binding.root.setOnClickListener {

        }
        binding.tvSubtractNum.setOnClickListener {
            num--
            setNumFormat()
        }
        initEditText()
        binding.tvAddNum.setOnClickListener {
            num++
            setNumFormat()
        }
        BtnList.forEach {
            it.setOnClickListener { v -> setBtn(v as AppCompatButton) }
        }
        setBtn(binding.btn1x)
        setNumFormat()
    }

    fun setData(n: Int, l: String) {
        num = n
        oldNum = n
        label = l
    }

    private fun setNumFormat() {
        if (num < 1) num = 1
        val i = num.toString()
        binding.tvNum.setText(i)
//        binding.tvNumLabel.text = label
    }

    private fun setBtn(n: AppCompatButton) {
        selectBtn = n
        for (b in BtnList) {
            if (selectBtn === b) {
                b.isSelected = true
                b.setTextColor(resources.getColor(R.color.white))
                var layoutP = b.layoutParams
                layoutP.width = (75 * density).toInt()
                b.layoutParams = layoutP
            } else {
                b.setTextColor(resources.getColor(R.color.black))
                b.isSelected = false
                var layoutP = b.layoutParams
                layoutP.width = (48 * density).toInt()
                b.layoutParams = layoutP
            }
        }
        when (selectBtn) {
            binding.btn1x -> num = oldNum
            binding.btn3x -> {
                num = oldNum * 3
                setNumFormat()
            }

            binding.btn5x -> {
                num = oldNum * 5
                setNumFormat()
            }
        }
        setNumFormat()
    }


    private fun initEditText() {
        binding.tvNum.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(inputContent: Editable?) {
                if (inputContent == null) return

                binding.tvNum.removeTextChangedListener(this) //移除输入监听，避免陷入死循环
                if (TextUtils.isEmpty(label)) {
                    runCatching {
                        num = inputContent.toString().toInt()
                    }
                } else {
                    if (inputContent.toString().trim() == label) {
                        //当此时内容是单位的时候，将edittext置为空
                        binding.tvNum.setText("")
                    } else {
                        var ss = inputContent.toString()
                        //辅助判断单位存不存在/存在的位置
                        val len = ss.length - label.length
                        if (len > 0 && ss.substring(
                                ss.length - label.length,
                                ss.length
                            ) == label
                        ) {
                            //单位就在最后不处理
                        } else {
                            //当用户自己将光标置到单位后面时，输入的内容就会在单位后面，此时将前面的单位去掉，将单位放到最后
                            ss = ss.replace(label, "") + label
                            binding.tvNum.setText(ss)
                            //这里得到光标应该在的位置（单位前面）
                            val index = ss.length - label.length
                            //设置光标的位置
                            Selection.setSelection(binding.tvNum.text, if (index < 0) 0 else index)
                        }
                        runCatching {
                            num = ss.replace(label, "").toInt()
                        }
                    }
                }
                //重新进行监听
                binding.tvNum.addTextChangedListener(this)
            }
        })
    }
}